package com.jh.paymentchannel.util.yipiaolian;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

public class CertUtil {
    private static final Logger logger = LoggerFactory.getLogger(CertUtil.class);

    private static final String PUBLIC_KEY_PATH = "/product/deploy/ypl_fg_public.cer";
    private static final String PRIVATE_KEY_PATH = "/product/deploy/ypl_fg_private.pfx";
    private static final String KEY_STORE_PASSWORD = "qq581511";
    private static final String KEY_TYPE = "PKCS12";

    private static KeyStore keyStore = null;
    private static PublicKey publicKey = null;

    static {
        try {
            keyStore = KeyStore.getInstance(KEY_TYPE);
            keyStore.load(new FileInputStream(PRIVATE_KEY_PATH), KEY_STORE_PASSWORD.toCharArray());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            java.security.cert.Certificate cert = cf.generateCertificate(new FileInputStream(PUBLIC_KEY_PATH));
            publicKey = cert.getPublicKey();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 获取加签私钥
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey() throws Exception {
        Enumeration<String> aliases = keyStore.aliases();
        String alias = "";
        while(aliases.hasMoreElements()) {
            alias = aliases.nextElement();
        }
        return (PrivateKey)keyStore.getKey(alias, KEY_STORE_PASSWORD.toCharArray());
    }

    /**
     * 获取解签公钥
     * @return
     * @throws Exception
     */
    public static PublicKey getUnSignPublicKey() throws Exception {
        return publicKey;
    }

    /**
     * 获取证书序列号
     * @return
     * @throws KeyStoreException
     */
    public static String getCertId() throws KeyStoreException {
        Enumeration<String> aliases = keyStore.aliases();
        String alias = "";
        while(aliases.hasMoreElements()) {
            alias = aliases.nextElement();
        }
        X509Certificate certificate = (X509Certificate)keyStore.getCertificate(alias);
        return certificate.getSerialNumber().toString();
    }
}
